#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
修复默认账户显示问题
直接修改账户管理器代码，确保默认账户能正确显示
"""
import os
import sys
import json

# 添加项目根目录到Python路径
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))


class SimpleLogger:
    """简单的日志类"""
    @staticmethod
    def info(msg):
        print(f"INFO: {msg}")
    
    @staticmethod
    def warning(msg):
        print(f"WARNING: {msg}")
    
    @staticmethod
    def error(msg):
        print(f"ERROR: {msg}")


logger = SimpleLogger()


def fix_default_account_display():
    """修复默认账户显示问题"""
    logger.info("=== 开始修复默认账户显示问题 ===")
    
    # 路径到账户配置文件
    config_path = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), 'config', 'accounts_config.json')
    
    # 确保配置目录存在
    config_dir = os.path.dirname(config_path)
    if not os.path.exists(config_dir):
        logger.info(f"创建配置目录: {config_dir}")
        os.makedirs(config_dir, exist_ok=True)
    
    # 读取现有的账户配置
    config = {}
    if os.path.exists(config_path):
        try:
            with open(config_path, 'r', encoding='utf-8') as f:
                config = json.load(f)
            logger.info(f"成功读取配置文件: {config_path}")
        except Exception as e:
            logger.error(f"读取配置文件失败: {str(e)}")
            config = {'accounts': {}, 'active_account_id': None}
    else:
        logger.warning(f"配置文件不存在，将创建新的配置文件: {config_path}")
        config = {'accounts': {}, 'active_account_id': None}
    
    # 确保默认账户存在
    accounts = config.get('accounts', {})
    if 'default' not in accounts:
        logger.info("默认账户不存在，创建默认账户...")
        accounts['default'] = {
            'account_id': 'default',
            'platform': 'tencent',
            'account_name': '默认账户',
            'description': '系统默认账户'
        }
    else:
        logger.info("默认账户已存在")
        # 确保默认账户信息完整
        default_account = accounts['default']
        required_fields = ['account_id', 'platform', 'account_name', 'description']
        for field in required_fields:
            if field not in default_account:
                logger.warning(f"默认账户缺少字段 '{field}'，补充中...")
                if field == 'account_id':
                    default_account[field] = 'default'
                elif field == 'platform':
                    default_account[field] = 'tencent'
                elif field == 'account_name':
                    default_account[field] = '默认账户'
                elif field == 'description':
                    default_account[field] = '系统默认账户'
    
    # 确保默认账户是活跃账户
    if config.get('active_account_id') != 'default':
        logger.info("设置默认账户为活跃账户")
        config['active_account_id'] = 'default'
    
    # 保存更新后的配置
    try:
        with open(config_path, 'w', encoding='utf-8') as f:
            json.dump(config, f, ensure_ascii=False, indent=2)
        logger.info(f"成功保存更新后的配置文件: {config_path}")
    except Exception as e:
        logger.error(f"保存配置文件失败: {str(e)}")
    
    # 创建一个简单的凭证文件（仅用于开发和显示目的）
    credentials_path = os.path.join(config_dir, 'api_credentials.json')
    if not os.path.exists(credentials_path):
        logger.info(f"创建演示用的API凭证文件: {credentials_path}")
        demo_credentials = {
            "api_key": "demo_api_key",
            "api_secret": "demo_api_secret",
            "created_at": "2025-01-01 00:00:00"
        }
        try:
            with open(credentials_path, 'w', encoding='utf-8') as f:
                json.dump(demo_credentials, f, ensure_ascii=False, indent=2)
            logger.info(f"成功创建演示用凭证文件")
        except Exception as e:
            logger.error(f"创建演示用凭证文件失败: {str(e)}")
    
    logger.info("=== 默认账户显示问题修复完成 ===")
    logger.info("请重新启动应用程序以查看效果")


if __name__ == "__main__":
    fix_default_account_display()